package main

import (
	"fmt"
	"net/http"
	"log"
	"bytes"
)

func launch() {
	fmt.Println("nuclear launch detected")
}

func main() {
	fmt.Println("Commencing coutdown")
	abort := make(chan int)
	canLunch := make(chan int)
	go isAbort(abort)
	go commencingCountDown(canLunch)
	select {
	case <-canLunch:

	case <-abort:
		fmt.Println("Launch aborted!")
		return
	}
	launch()
}

func commencingCountDown(canLunch chan int) {
	//c := time.Tick(1 * time.Second)
	//for countDown := 20; countDown > 0; countDown-- {
	//	fmt.Println(countDown)
	//	<-c
	//}
	//canLunch <- -1
	http.HandleFunc("/", sayHello)
	err := http.ListenAndServe(":9090", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
	canLunch <- -1
}

func isAbort(abort chan int) {
	//c := time.Tick(1 * time.Second)
	//for countDown := 20; countDown > 0; countDown-- {
	//	fmt.Println("---",countDown)
	//	<-c
	//}
	//os.Stdin.Read(make([]byte, 1))
	//abort <- - 1
	http.HandleFunc("/w", sayHello)
	err := http.ListenAndServe(":19090", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
	abort <- - 1
}
func sayHello(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	fmt.Println(r.Form)
	fmt.Println(r.URL.Host)
	fmt.Println(r.URL.Scheme)
	fmt.Println(r.URL.Path)
	fmt.Println(r.Form["name"])
	var nameVal string
	for k, v := range r.Form {
		fmt.Println("key:", k)
		if k == "name" {
			nameVal = v[0]
		}
		fmt.Println("value:", v)
	}
	s := AppendStr("Hello", " ", nameVal)
	fmt.Println(w, s)
	w.Write([]byte(s))
}

func AppendStr(s ... string) string {
	var bf bytes.Buffer
	for i := 0; i < len(s); i++ {
		bf.WriteString(s[i])
	}
	fmt.Println(bf.String())
	return bf.String()
}
